#
# LMusicDownloader.py
#

from qt import *
from kdecore import *
from kio import *
from LMusicImporter import *

class LMusicDownloader(QObject):
	def __init__(self):
		QObject.__init__(self)
		self.queue = []
		self.currentJob = None
		self.currentItem = None
	
	def downloadTracks(self,tracks,playlist,library = None):
		if len(self.queue)==0:
				self.status({'Source':'Downloader','Status':'Begin'});
				self.total = 0
				self.index = 0
		for track in tracks:
			self.queue.append({'Track':track,'Playlist':playlist,'Library':library})
		self.total = self.total+len(self.queue)
		self.downloadNextTrack()
	
	def status(self,status):
		self.emit(PYSIGNAL("status"),(status,None))
		
	def downloadNextTrack(self):
		if self.currentJob==None:
			if len(self.queue)!=0:
				self.index = self.index+1 
				self.currentItem = self.queue[0]
				self.queue = self.queue[1:]
				track = self.currentItem['Track']
				#print "downloading",track.location,track.shortName
				kurl = KURL(track.location)
				self.currentJob = KIO.get(kurl,False,False)
				self.currentJob.shortName = track.title
				QObject.connect(self.currentJob,SIGNAL('data(KIO::Job *,const QByteArray &)'),self.onData)
				QObject.connect(self.currentJob,SIGNAL('result(KIO::Job *)'),self.onResult)
				QObject.connect(self.currentJob,SIGNAL('percent (KIO::Job *, unsigned long)'),self.onPercent)
				self.currentJob.fileName = "/tmp/%s" % track.shortName
				#print "writing to file",self.currentJob.fileName
				self.currentJob.file = open(self.currentJob.fileName,"wb")
				self.currentJob.resume()
			else:
				#print "downloading complete"
				self.status({'Source':'Downloader','Status':'End'})
		else:
			print "downloader busy"
	
	def onData(self,job,bytes):
		try: self.currentJob.file.write(str(bytes))
		except: print "problem writing bytes"
		#print "download got %d bytes" % len(str(bytes))
	
	def onResult(self,job):
		#print "done"
		try: self.currentJob.file.close()
		except: pass
		LMusicImporter.singleton().importFiles([self.currentJob.fileName],self.currentItem['Library'],self.currentItem['Playlist'],True)
		self.currentJob = None
		self.currentItem = None
		self.downloadNextTrack()
	
	def onPercent(self,job,percent):
		#print "percent %d%%" % percent
		self.status({'Source':'Downloader','Status':'Downloading','currentTime':percent,'totalTime':100,'Track':self.currentJob.shortName,'Index':self.index,'Count':self.total})

	def cancelDownloads(self):
		self.queue = []
		self.currentItem = None
		self.currentJob = None
	
	def static_singleton():
		global _musicDownloaderSingleton
		if _musicDownloaderSingleton==None:
			_musicDownloaderSingleton = LMusicDownloader()
		return _musicDownloaderSingleton
	
	singleton = staticmethod(static_singleton)

_musicDownloaderSingleton = None
